
import cgi,datetime,logging,sys
from google.appengine.ext import db
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import run_wsgi_app

logging.basicConfig(level=logging.DEBUG)

# Model
class PostData(db.Model):
    u_filename = db.StringProperty(multiline=False)
    u_date     = db.DateTimeProperty(auto_now_add=True)

class PostDataChunk(db.Model):
    master= db.ReferenceProperty(PostData)
    seq   = db.IntegerProperty()
    chunk = db.BlobProperty()

# View(Logic)
class Root(webapp.RequestHandler):
    def get(self):
        # info to hand to template
        info = dict()
        query_str = "SELECT * FROM PostData ORDER BY u_date DESC LIMIT 50"
        datum = db.GqlQuery (query_str)
        items = []
        for data in datum:
            iteminfo={}
            iteminfo['id'] = data.key()
            iteminfo['filename'] = cgi.escape(data.u_filename)
            iteminfo['date'] = data.u_date.strftime("%Y/%m/%d %H:%M:%S")
            items.append(iteminfo)
        info['items'] = items

        # hand it out to template
        t = template.Template(TMPL_ROOT)
        self.response.out.write(t.render(template.Context(info)))

class Upload(webapp.RequestHandler):
    def post(self):
        filename = self.request.headers['filename']
        postdata = PostData(key_name=filename)
        # collect information
        postdata.u_filename = filename
        # commit
        postdata.put()

        # now real data
        filedata = self.request.body
        for i in range( len(filedata) / 500000 + 1):
            chunk = PostDataChunk()
            chunk.master = postdata.key()
            chunk.seq = i
            chunk.chunk = db.Blob(filedata[i*500000:(i+1)*500000 ])
            chunk.put()

        # record to store
        self.redirect('/img_list')

class Download(webapp.RequestHandler):
    def get(self):
        postdata = PostData.get_by_key_name(self.request.get("name"))
        mime = "image/png"
        self.response.headers['Content-Type'] = mime
        query = PostDataChunk.gql("where master = :master order by seq", master=postdata.key() )
        for r in query.fetch(1000):
            self.response.out.write(r.chunk)

class Delete(webapp.RequestHandler):
    def get(self):
        postdata = PostData.get_by_key_name(self.request.get("name"))
        query = PostDataChunk.gql("where master = :master order by seq", master=postdata.key() )
        for r in query.fetch(1000):
            r.delete()
        postdata.delete()
        self.redirect('/img_list')

# Template
TMPL_ROOT="""
<html> <body>
    <p> GAE Simple Uploader (Upload Limit: 10MB) </p>
        
            <table border="1" >
            <tr><td>filename</td><td>upload at</td><td>DELETE</td></tr>
            {% for item in items %}
            <tr>
                <td> <a href="/img_download/?name={{item.filename}}">{{item.filename}}</a></td>
                <td> {{item.date}}</td>
                <td> <a href="/img_delete/?name={{item.filename}}">Delete</a></td>
            </tr>
           {% endfor %}
            </table>
            <br>
    </body> </html>"""

# WSGI
application = webapp.WSGIApplication([
        ('/img_list', Root),
        ('/img_upload', Upload),
        ('/img_download/.*', Download),
        ('/img_delete/.*', Delete),
        ], debug=True)

def main():
    run_wsgi_app(application)

if __name__ == '__main__':
    main()
